package top.i89ck.modules.handler;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局拦截器
 * @author Seiya
 */
public class GlobalInterceptor implements Interceptor {

    private final static String HTTP = "http";
    private final static String HTTPS = "https";


    @Override
    public void intercept(Invocation inv) {
        Controller controller = inv.getController();
        String rootPath = getRootPath(controller);
        controller.set("baseUrl", rootPath);
        inv.invoke();
    }

    /**
     * 获取项目根路径
     *
     * @param controller
     * @return
     */
    public String getRootPath(Controller controller) {
        HttpServletRequest request = controller.getRequest();
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        String contextPath = request.getContextPath();

        StringBuilder rootPath = new StringBuilder();
        rootPath.append(scheme).append("://").append(serverName);

        if (!isDefaultPort(scheme, serverPort)) {
            rootPath.append(":").append(serverPort);
        }

        rootPath.append(contextPath);

        return rootPath.toString();
    }

    /**
     * 判断端口号是否是默认端口号
     *
     * @param scheme
     * @param serverPort
     * @return
     */
    private boolean isDefaultPort(String scheme, int serverPort) {
        return (HTTP.equals(scheme) && serverPort == 80) || (HTTPS.equals(scheme) && serverPort == 443);
    }
}
